package job.work.utils;/**
 * @Classname UploadDowload
 * @Description zzy
 * @Date 2020/7/6 16:19
 * @Created by Administrator
 */

import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class UploadDowload {

    private static final long serialVersionUID = 1L;


    //日志
    Logger logger = LoggerFactory.getLogger(UploadDowload.class);



    @Transactional

    public String upload(MultipartFile file) {
        long startTime = System.currentTimeMillis();
        try {


            StorageClient1 storageClient1 = config();
            //上传文件
            //得到文件字节
            byte[] bytes = file.getBytes();
            //得到文件的原始名称
            String originalFilename = file.getOriginalFilename();
            //得到文件扩展名
            String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String fileId = storageClient1.upload_file1(bytes, ext, null);
           // String uploadPath = "https://www.scjum.com:8391/" + fileId;
            return "https://www.scjum.com:8391/" + fileId;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上传出现异常[{}ms]", System.currentTimeMillis() - startTime, e.getMessage());
        }
        return null;
    }



    /**
     * 设置响应头  文件类型为zip的   可以修改对应的后缀
     */
    public static void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            int i = fileName.indexOf(".");
            //  String substring = fileName.substring(i + 1); //后缀名
            response.reset();// 清空输出流
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String(fileName.getBytes("GB2312"), "8859_1"));
//                    + substring);substring 就是为 文件类型
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    //获取fastDFS 路径后面 的全称
    private String group(String url) {

        Pattern pattern = Pattern.compile("/");
        Matcher findMatcher = pattern.matcher(url);
        int lengthCut = 0;
//        int lengthEnd = 0;

        while (findMatcher.find()) {
            lengthCut++;
            if (lengthCut == 3) {//当“/”第三次出现时停止
                break;
            }
        }
        int i = findMatcher.start();//“/”第三次出现的位置
        return url.substring(i + 1);
    }

    private StorageClient1 config() throws Exception {
        //加载fastdfs-client.properties配置文件
           ClientGlobal.initByProperties("config/fastdfs-client.properties");

//        ClientGlobal.init(CONF_FILENAME);
        //定义TrackerClient，用于请求TrackerServer
        TrackerClient trackerClient = new TrackerClient();
        //得到storage服务器
        TrackerServer trackerServer = trackerClient.getConnection();

        StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
        //创建storageClient来上传文件
//        StorageClient1 storageClient1 = new StorageClient1(trackerServer, storeStorage);

        return new StorageClient1(trackerServer, storeStorage);
    }

}
